package com.hilon.segment.mybatis.dao.impl;



import com.hilon.segment.mybatis.dao.IBaseDao;
import com.hilon.segment.mybatis.utils.ProJPAUtil;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class BaseDaoImpl<T> implements IBaseDao<T> {
    private Class<T> clz;
    public static EntityManager manager = ProJPAUtil.getEntityManager();

    static {
        manager.getTransaction().begin();
    }

    public BaseDaoImpl() {
        //这里用到反射的原理动态获取类型
        //传进来什么类型这里就获得什么类型的class
        ParameterizedType parameterClass = (ParameterizedType) this.getClass().getGenericSuperclass();
        //获得类型的数组，这里只传进来了一个不确定类型T类型
        Type[] actualTypeArguments = parameterClass.getActualTypeArguments();
        //第一个就是传进来的class
        clz = (Class<T>) actualTypeArguments[0];
    }

    @Override
    public void save(T o) {
        manager.persist(o);
        manager.getTransaction().commit();
        manager.close();
    }

    @Override
    public void update(T o) {
        manager.merge(o);
        manager.getTransaction().commit();
        manager.close();
    }

    @Override
    public void delete(Serializable i) {
        System.out.println(i);
        T t = manager.find(clz, i);
        manager.remove(t);
        manager.getTransaction().commit();
        manager.close();
    }

    @Override
    public List<T> getAll() {
        String sql = "select p from " + clz.getName() + " as p";
        Query query = manager.createQuery(sql);
        List list = query.getResultList();
        return list;
    }

    @Override
    public T getOne(Serializable i) {
        T t = manager.find(clz, i);
        return t;
    }
}